﻿namespace c0x3y.StyleCopFixer.Errors
{
    using System.Collections.Generic;
    using EnvDTE;
    using EnvDTE80;
    using System.Text.RegularExpressions;
    using c0x3y.StyleCopFixer.Interfaces;

    public class SA1200
    {
        public static void Run(EnvDTE.DTE dte, ErrorItem selectedError)
        {
            List<string> filesProcessed = new List<string>();
            if (filesProcessed.IndexOf(selectedError.FileName) == -1)
            {
                selectedError.Navigate();
                EditPoint2 ep = ErrorUtilities.GetEditPoint(dte);
                ep.StartOfDocument();

                bool namespaceFound = false;
                List<string> usedNamespaces = new List<string>();
                while (!namespaceFound)
                {
                    if (string.IsNullOrEmpty(ep.GetLines(ep.Line, ep.Line + 1)))
                    {
                        ep.Delete(1);
                    }
                    else if (ep.GetLines(ep.Line, ep.Line + 1).StartsWith("using "))
                    {
                        usedNamespaces.Add(ep.GetLines(ep.Line, ep.Line + 1));
                        ep.Delete(ep.LineLength);
                    }
                    else if (ep.GetLines(ep.Line, ep.Line + 1).StartsWith("namespace "))
                    {
                        namespaceFound = true;
                    }
                    else
                    {
                        ep.LineDown();
                    }
                }

                // Mode to the fist curly bracket (this should be the one within the namespace
                while (ep.GetLines(ep.Line, ep.Line + 1).IndexOf("{") == -1)
                {
                    ep.LineDown();
                }

                ep.LineDown();
                for (int i = 0; i < usedNamespaces.Count; i++)
                {
                    ep.StartOfLine();
                    ep.Insert(usedNamespaces[i]);
                    ep.Indent(Count: 1);
                    ep.InsertNewLine();
                }

                ep.InsertNewLine();
                filesProcessed.Add(selectedError.FileName);
            }
        }
    }
}
